package org.example.controller;

import org.example.client.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author limeng
 * @create 2021-05-25 16:50
 */
@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private DiscoveryClient discoveryClient; //服务发现客户端

    @Autowired
    private  LoadBalancerClient loadBalancerClient; //负载均衡客户端组件

    @Autowired
    private RestTemplate restTemplate; //这个对象是具有负载均衡的restTemplate

    @Value("${server.port}")
    private Integer port;

    @Autowired
    private ProductClient productClient;

    @GetMapping("/user/test")
    public String test() {
        log.info("调用用户服务成功");

        //使用ribbon组件实现负载均衡 DiscoverClient LoadBalanceClient @Load
        //1.使用DiscoveryClient
        //List<ServiceInstance> serviceInstances = discoveryClient.getInstances("PRODUCTS");
        //for (ServiceInstance serviceInstance : serviceInstances) {
        //    log.info("服务主机：{} 服务端口：{} 服务uri：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
        //}

        //2.使用LoadBalancerClient 好处：已经进行负载均衡之后的返回结点
        //ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCTS");

        //上面DiscoveryClient方式不好，需要自己手动做负载均衡（轮询策略）
        //String result = new RestTemplate().getForObject(serviceInstance.getUri() + "/product/test/1", String.class);

        //3.使用@LoadBalanced注解
        //String result = restTemplate.getForObject("http://PRODUCTS/product/test/1", String.class);

        //使用openFeign实现服务调用
        String result = productClient.test(1);

        log.info(result);
        return result;
    }
}
